import axios from 'axios';

const API_URL = 'http://localhost:3000/api/auth';

// 请求拦截器 - 添加令牌到请求头
axios.interceptors.request.use(
    (config) => {
        const token = localStorage.getItem('accessToken');
        if (token) {
            config.headers['Authorization'] = `Bearer ${token}`;
        }
        return config;
    },
    (error) => Promise.reject(error)
);

// 响应拦截器 - 处理令牌过期
axios.interceptors.response.use(
    (response) => response,
    async (error) => {
        const originalRequest = error.config;

        // 如果是401错误且不是刷新token的请求且未尝试过刷新
        if (error.response?.status === 401
            && !originalRequest._retry
            && !originalRequest.url?.includes('/refresh')
            && localStorage.getItem('refreshToken')) {

            originalRequest._retry = true;

            try {
                // 尝试刷新令牌
                const refreshToken = localStorage.getItem('refreshToken');
                const response = await axios.post(`${API_URL}/refresh`, {}, {
                    headers: {
                        'Refresh-Token': refreshToken
                    }
                });

                // 更新储存的令牌
                const { token } = response.data.data;
                localStorage.setItem('accessToken', token);

                // 更新原始请求的认证头
                originalRequest.headers['Authorization'] = `Bearer ${token}`;

                // 重试原始请求
                return axios(originalRequest);
            } catch (refreshError) {
                // 刷新失败，需要重新登录
                localStorage.removeItem('accessToken');
                localStorage.removeItem('refreshToken');
                localStorage.removeItem('user');
                window.location.href = '/login';
                return Promise.reject(refreshError);
            }
        }

        return Promise.reject(error);
    }
);

// 模拟API响应 - 当后端API不可用时使用
const useMockApi = false; // 设置为true启用模拟API，生产环境记得设为false

// 用户注册
const register = async (username, email, password) => {
    try {
        if (useMockApi) {
            // 模拟成功响应
            console.log('使用模拟API进行注册:', { username, email, password });
            const mockResponse = {
                data: {
                    message: "注册成功",
                    data: {
                        userId: "mock-user-123",
                        token: "mock-token-xyz",
                        username: username
                    }
                }
            };

            // 模拟延迟
            await new Promise(resolve => setTimeout(resolve, 800));

            localStorage.setItem('accessToken', mockResponse.data.data.token);
            localStorage.setItem('user', JSON.stringify({
                id: mockResponse.data.data.userId,
                username,
                email
            }));

            return mockResponse.data;
        }

        // 原有的API调用代码
        const response = await axios.post(`${API_URL}/register`, {
            username,
            email,
            password
        });

        if (response.data.data.token) {
            localStorage.setItem('accessToken', response.data.data.token);
            localStorage.setItem('user', JSON.stringify({
                id: response.data.data.userId,
                username,
                email
            }));
        }

        return response.data;
    } catch (error) {
        console.error('注册错误:', error);
        throw error.response?.data || error;
    }
};

// 用户登录
const login = async (username, password) => {
    try {
        if (useMockApi) {
            // 模拟成功响应
            console.log('使用模拟API登录:', { username, password });
            const mockResponse = {
                data: {
                    message: "登录成功",
                    data: {
                        token: "mock-token-xyz",
                        refreshToken: "mock-refresh-token",
                        username: username
                    }
                }
            };

            // 模拟延迟
            await new Promise(resolve => setTimeout(resolve, 800));

            localStorage.setItem('accessToken', mockResponse.data.data.token);
            localStorage.setItem('refreshToken', mockResponse.data.data.refreshToken);
            localStorage.setItem('user', JSON.stringify({
                username,
            }));

            return mockResponse.data;
        }

        // 原有的API调用代码
        const response = await axios.post(`${API_URL}/login`, {
            username,
            password
        });

        console.log('登录响应:', response.data);

        if (response.data && response.data.data && response.data.data.token) {
            localStorage.setItem('accessToken', response.data.data.token);
            localStorage.setItem('refreshToken', response.data.data.refreshToken);
            localStorage.setItem('user', JSON.stringify({
                username,
                // 可以从response.data.data添加其他用户信息
            }));
        }

        return response.data;
    } catch (error) {
        console.error('请求错误:', error);
        if (error.response) {
            console.error('响应数据:', error.response.data);
            console.error('响应状态:', error.response.status);
        }
        throw error.response?.data || error;
    }
};

// 刷新令牌
const refreshToken = async () => {
    const token = localStorage.getItem('accessToken');
    const refreshToken = localStorage.getItem('refreshToken');

    if (!token || !refreshToken) {
        throw new Error('No tokens found');
    }

    try {
        const response = await axios.post(`${API_URL}/refresh`, {}, {
            headers: {
                'Authorization': `Bearer ${token}`,
                'Refresh-Token': refreshToken
            }
        });

        localStorage.setItem('accessToken', response.data.data.token);
        return response.data;
    } catch (error) {
        throw error.response?.data || error;
    }
};

// 注销
const logout = () => {
    localStorage.removeItem('accessToken');
    localStorage.removeItem('refreshToken');
    localStorage.removeItem('user');
};

// 获取当前用户
const getCurrentUser = () => {
    const userStr = localStorage.getItem('user');
    if (!userStr) return null;
    return JSON.parse(userStr);
};

// 检查是否已认证
const isAuthenticated = () => {
    return !!localStorage.getItem('accessToken');
};

const authService = {
    register,
    login,
    refreshToken,
    logout,
    getCurrentUser,
    isAuthenticated
};

export default authService; 